import request from "../../../utils/request"
import PubSub from 'pubsub-js'
Page({

  data:{
    day:"",
    month:"",
    recommendSongList:[],
    index:""//当前音乐的下标
  },

  onLoad(){
    //判断是否登录 
    let userInfo = wx.getStorageSync('profile')
    if(!userInfo){//cookies为空
      wx.showToast({
        title: '请先登录...',
        icon:'none',
        success:()=>{
          wx.reLaunch({
            url: '/pages/login/login',
         })
        }
      })
    }
    this.getDate();
    this.getRecommendSongList();
    PubSub.subscribe("switchtype",(event,type)=>{
      //获取当前音乐的index
      let {recommendSongList,index} = this.data;
      if(type === "next"){
        index++;
        if(index > recommendSongList.length-1){
          index = 0;
        }
      }else if(type === "pre"){
        index--;
        if(index <0){
          index = recommendSongList.length-1;
        }
      }
      //更新最新的index值
      this.setData({
        index
      })
      //获取下一首音乐的id并传给songdetail
      console.log(recommendSongList[index].id)
      PubSub.publish('musicId',recommendSongList[index].id)
    })
  },
  //获取日期
  getDate(){
    let date = new Date();
    this.setData({
      month:date.getMonth()+1,
      day:date.getDate()
    })
  },
  //获取推荐歌曲数据
  async getRecommendSongList(){
    let recommendSongList = await request("/recommend/songs")
    // console.log(recommendSongList)
    this.setData({
      recommendSongList:recommendSongList.recommend
    })
  },
  toSongDetail(event){
    let ids =event.currentTarget.id;
    //获取当前歌曲元素的下标
    let index = event.currentTarget.dataset.index;

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/songPackage/pages/songdetail/songdetail?ids='+ ids,
    })
  }

})